﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

using CAUNetLogin.Entity;
using CAUNetLogin.Util.SystemLib;
using CAUNetLogin.Util.Validate;
using CAUNetLogin.Util.Security;
using System.Net;
using CAUNetLogin.NetUtil.ReturnMessage;
using CAUNetLogin.Util.Entity;
using CAUNetLogin.Util.SystemLib.Tools;

namespace CAUNetLogin
{
    public partial class CAULogin : Form
    {
        public Account user;
        public NetState netState;
        public SucceedMessage succeedMsg;
        public FailedMessage failedMsg;
        public NetConnect netConnect;
        private string killedWindowName;

        public CAULogin()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 加载初始化信息,包含用户名、密码、是否开机启动、自动连接、自动连接后退出
        /// </summary>

        public void LoadInitData()
        {
            netState = new NetState();
            user = new Account();
            succeedMsg = new SucceedMessage();
            failedMsg = new FailedMessage();
            netConnect = new NetConnect();

            netState.GetNetState();
            toolStripStatusNetStateType.Text = netState.netStateMessage;
            if (File.Exists(ConfigManager.configFilePath))
            {
                ConfigManager.GetAccount(ref user);
                checkBoxSavePassword.Checked = true;
                ConfigManager.savePassword = true;
                SetAccount();
            }
            notifyIcon.Visible = true;
            if (ConfigManager.CheckAutoStart(ConfigManager.autoRunKeyName))
            {
                checkBoxWindowStart.Checked = true;
                ConfigManager.startWithWindows = true;
            }
            if (!ConfigManager.runAsAdministrator)
            {
                checkBoxWindowStart.Enabled = false;
                checkBoxWindowStart.Text = "开机启动(请管理员权限运行)";
            }

            if (Registery.CUCheckRegistery(@"Software\CAUNetLogin", "ExitAfterConnect", "1"))
            {
                checkBoxExitAfterConnect.Checked = true;
                ConfigManager.exitAfterConnect = true;
            }
            if (Registery.CUCheckRegistery(@"Software\CAUNetLogin", "AutoConnect", "1"))
            {
                checkBoxAutoConnect.Checked = true;
                ConfigManager.autoConnect = true;
            }
        }

        public void GetAccount()
        {
            user.User = textBoxUserID.Text;
            user.Password = textBoxPassword.Text;
        }

        public void SetAccount()
        {
            textBoxUserID.Text = user.User;
            textBoxPassword.Text = user.Password;
        }


        private void buttonConnect_Click(object sender, EventArgs e)
        {
            Connect();
        }

        public void Connect()
        {

            if (DataValidate.IsEmpty(textBoxUserID.Text))
            {
                MessageBox.Show("账户不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (DataValidate.IsEmpty(textBoxPassword.Text))
            {
                MessageBox.Show("密码不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (checkBoxSavePassword.Checked)
            {
                GetAccount();
                ConfigManager.SaveAccount(user);
            }
            if (checkBoxSavePassword.Checked == false && File.Exists(ConfigManager.configFilePath))
            {
                File.Delete(ConfigManager.configFilePath);
            }
            if (netState.GetNetState())
            {
                if (netState.Ping("121.195.178.238", "121.194.0.239"))
                {
                    toolStripStatusNetState.Text = "网络已经连接,不要重复连接!";
                    MessageBox.Show("网络已经连接,不要重复连接!", "网络状况", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string result = "获取流量信息失败";
                if (netConnect.ConnectSucceed(user, ref result))
                {
                    succeedMsg.ParseMsg(result);
                    toolStripStatusNetState.Text = "网络连接成功!";
                    string msg = "网络已成功连接!\n剩余可用流量:" + succeedMsg.flowRemained + "MB\n余额：" + succeedMsg.balance + "元\n已使用流量:" + succeedMsg.flowUsed + "MB\n";
                    if (succeedMsg.ParseMsg(result) && !ConfigManager.exitAfterConnect)
                    {

                        FlowForm flowForm = new FlowForm(succeedMsg);
                        flowForm.Show();
                        PopupWindow.SetWindowPos(flowForm.Handle, 100, Screen.PrimaryScreen.Bounds.Width - flowForm.Width, Screen.PrimaryScreen.Bounds.Height - flowForm.Height - 30, 50, 50, 1);//设置弹出位置
                        PopupWindow.AnimateWindow(flowForm.Handle, 500, PopupWindow.AW_VER_NEGATIVE);//设置弹出的动作
                        setTimerKiller("流量信息", 5000);
                    }


                        if (ConfigManager.exitAfterConnect)//连接后退出程序
                    {
                        setTimerKiller("网络状况", 2000);
                        MessageBox.Show(msg, "网络状况", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Application.Exit();
                    }
                }
                else
                {
                    failedMsg.ParseMsg(result);
                    toolStripStatusNetState.Text = "网络连接失败!" + failedMsg.msg;
                    MessageBox.Show("网络连接失败!\n" + failedMsg.msg, "网络状况", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                toolStripStatusNetState.Text = "网络异常,请检查网线等上网设备";
                MessageBox.Show("网络异常,请检查网线等上网设备", "网络状况", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 断开网络连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            if (!netState.Ping("121.195.178.238", "121.194.0.239"))
            {
                toolStripStatusNetState.Text = "网络已断开,请不要重复断开!";
                MessageBox.Show("网络已断开,请不要重复断开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (netConnect.DisConnect())
            {
                toolStripStatusNetState.Text = "网络已成功断开!";
                MessageBox.Show("网络已成功断开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                toolStripStatusNetState.Text = "网络断开失败!";
                MessageBox.Show("网络断开失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }





        /// <summary>
        /// 在窗体显示前加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CAULogin_Shown(object sender, EventArgs e)
        {
            if (ConfigManager.autoConnect)
            {
                Connect();
            }
        }


        /// <summary>
        /// 在窗体显示前加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CAULogin_Load(object sender, EventArgs e)
        {
            LoadInitData();
        }





        /**
         * setTimerKiller，timerKiller_Tick函数为定时关闭一个打开的窗口
         */
        public void setTimerKiller(string windowName, int millsecond)
        {
            this.killedWindowName = windowName;
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = millsecond;
            timer.Tick += new EventHandler(timerKiller_Tick);
            timer.Start();
        }

        private void timerKiller_Tick(object sender, EventArgs e)
        {
            SystemWindow.KillWindows(killedWindowName);
            ((System.Windows.Forms.Timer)sender).Stop();
            sender = null;
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            textBoxUserID.Text = "";
            textBoxPassword.Text = "";
        }

        private int WM_SYSCOMMAND = 0x112;
        //private long SC_MAXIMIZE = 0xF030;
        private long SC_MINIMIZE = 0xF020;
        private long SC_CLOSE = 0xF060;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                if (m.WParam.ToInt64() == SC_MINIMIZE)
                {
                    this.Hide();
                    notifyIcon.BalloonTipTitle = "提示";
                    notifyIcon.BalloonTipText = "CAU网关登录器小化到此处";
                    notifyIcon.ShowBalloonTip(1000);
                    return;
                }
            }
            base.WndProc(ref m);
        }



        private void buttonMore_Click(object sender, EventArgs e)
        {
            if (((Button)sender).Text.Equals(">>"))
            {
                ((Button)sender).Text = "<<";
                groupBoxMoreSettings.Visible = true;
                groupBoxMoreSettings.Enabled = true;
                groupBoxButton.Visible = false;
                groupBoxButton.Enabled = false;
            }
            else
            {
                ((Button)sender).Text = ">>";
                groupBoxMoreSettings.Visible = false;
                groupBoxMoreSettings.Enabled = false;
                groupBoxButton.Visible = true;
                groupBoxButton.Enabled = true;
            }
        }

        /// <summary>
        /// checkbox有更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckboxUpdate(object sender, EventArgs e)
        {
            string result = "";
            if (ConfigManager.UpdateChoice(checkBoxSavePassword.Checked, checkBoxWindowStart.Checked, checkBoxAutoConnect.Checked, checkBoxExitAfterConnect.Checked, ref result, user))
            {
                MessageBox.Show(result, "状态更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(result, "状态更新失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 获取流量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSelf_Click(object sender, EventArgs e)
        {
            if (!netState.Ping("121.195.178.238", "121.194.0.239"))
            {
                MessageBox.Show("请先登录网关", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            GetFlowInfo();
            setTimerKiller("流量信息",5000);
        }

        /// <summary>
        /// 获得流量信息
        /// </summary>
        public void GetFlowInfo()
        {
            string result = "";
            netConnect.GetFlowInfo(ref result);
            if (succeedMsg.ParseMsg(result))
            {

                FlowForm flowForm = new FlowForm(succeedMsg);
                flowForm.Show();
                flowForm.BringToFront();
                PopupWindow.SetWindowPos(flowForm.Handle, 100, Screen.PrimaryScreen.Bounds.Width - flowForm.Width, Screen.PrimaryScreen.Bounds.Height - flowForm.Height - 30, 50, 50, 1);//设置弹出位置
                PopupWindow.AnimateWindow(flowForm.Handle, 500, PopupWindow.AW_VER_NEGATIVE);//设置弹出的动作
            }
        }

        private void 流量信息网页版ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!netState.Ping("121.195.178.238", "121.194.0.239"))
            {
                MessageBox.Show("请先登录网关", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string url = "http://auth.cau.edu.cn/";
            Browser b = new Browser(url);
            b.Show();
        }

        private void 反馈RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string title = "【CAU网关登录器】意见反馈";
            string url = "http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=h7W_srO3srOwtMf29qnk6Oo";
            Browser feedBack = new Browser(title, url);
            feedBack.Show();
        }

        private void 自助服务SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string url = "http://202.205.80.174/Self/LoginFromGatewayAction?DDDDD=" + textBoxUserID.Text.Trim() + "&upass=" + textBoxPassword.Text.Trim() + "&R1=0&R2=0&para=00&0MKKey=123456";
            Browser self = new Browser(url);
            self.Show();
        }

        private void 在线更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string title = "【CAU网关登录器】在线更新";
            string url = "https://caunetlogin.codeplex.com/releases";
            Browser feedBack = new Browser(title, url);
            feedBack.Show();
        }


        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            this.Dispose(true);
            Application.Exit();
        }

        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void 隐藏HToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void 显示SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.BringToFront();
        }

        private void 教务系统JToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Browser urp = new Browser("http://202.205.91.62/");
            urp.Show();
        }

        /// <summary>
        ///删除所有配置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteAllInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除所有配置信息?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (File.Exists(ConfigManager.configFilePath))
                {
                    File.Delete(ConfigManager.configFilePath);
                    checkBoxSavePassword.Checked = false;
                    checkBoxAutoConnect.Checked = false;
                    checkBoxExitAfterConnect.Checked = false;
                    checkBoxWindowStart.Checked = false;
                    textBoxUserID.Text = "";
                    textBoxPassword.Text = "";
                    string result = "";
                    if (ConfigManager.UpdateChoice(checkBoxSavePassword.Checked, checkBoxWindowStart.Checked, checkBoxAutoConnect.Checked, checkBoxExitAfterConnect.Checked, ref result, user))
                    {
                        MessageBox.Show("所有配置信息均已删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("配置信息删除失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }


        private void 锁定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setTimerKiller("锁定到任务栏", 5000);
            if (Widget.PinToTaskBar(true, Application.ExecutablePath))
            {
                MessageBox.Show("锁定程序到任务栏成功，可以快速从任务栏启动了", "锁定到任务栏", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("锁定程序到任务栏失败，请重新锁定或手动锁定(或者已经在任务栏锁定)", "锁定到任务栏", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }


        private void 解锁ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setTimerKiller("从任务栏解锁", 5000);
            if (Widget.PinToTaskBar(false, Application.ExecutablePath))
            {
                MessageBox.Show("从任务栏解锁成功", "从任务栏解锁", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("从任务栏解锁失败，请重新或手动解锁", "从任务栏解锁", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

    }
}
